<template>
  <PageWrapper
    content="用户持有的服务器列表"
    contentBackground
    contentClass="p-4"
    title="服务器列表"
  >
    <BasicTable
      :bordered="true"
      :canResize="false"
      :striped="true"
      showTableSetting
      @register="registerTable"
    >
      <template #toolbar>
        <a-button type="primary" @click="openAddObjectModel">登记全新机器</a-button>
        <a-button type="primary" @click="openAddObjectByTokenModel">登记已有机器</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:info-standard-line',
              tooltip: '查看服务器详情',
              onClick: handleView.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <AddObjectDialog
      @register="registerAddObject"
      :minHeight="100"
      @exitAddObject="exitAddObject"
    />
    <GetObjectByToken
      @register="registerAddObjectByToken"
      :minHeight="100"
      @exitAddObjectByToken="exitAddObjectByToken"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { tableColumns, tableSearch } from '/@/views/object/list/schema';
  import { listObjects } from '/@/api/monitor/object';
  import { PageWrapper } from '/@/components/Page';
  import { useGo } from '/@/hooks/web/usePage';
  import { useModal } from '/@/components/Modal';
  import AddObjectDialog from '/@/views/object/add/AddObjectDialog.vue';
  import GetObjectByToken from '/@/views/object/get/get-object/GetObjectByToken.vue';
  import { StdResponse } from '/@/api/model/baseModel';
  import { useMessage } from '/@/hooks/web/useMessage';

  const go = useGo();
  // for list
  const [registerTable, { reload: reloadObject }] = useTable({
    api: listObjects,
    columns: tableColumns,
    rowKey: 'id',
    useSearchForm: true,
    formConfig: {
      labelWidth: 75,
      baseColProps: {
        xl: 12,
        xxl: 8,
      },
      schemas: tableSearch,
      autoAdvancedLine: 10,
    },
    actionColumn: {
      width: 150,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  function handleView(record: Recordable) {
    go(`/object/${record.id}`, false);
  }
  const { createMessage } = useMessage();

  const [registerAddObject, { openModal: openAddObjectModal }] = useModal();

  async function openAddObjectModel() {
    openAddObjectModal(true);
  }

  function exitAddObject() {
    reloadObject();
  }

  const [registerAddObjectByToken, { openModal: openAddObjectByTokenModal }] = useModal();

  async function openAddObjectByTokenModel() {
    openAddObjectByTokenModal(true, {});
  }

  function exitAddObjectByToken(rsp: StdResponse) {
    reloadObject();
    if (rsp.code) {
      createMessage.error(`添加机器失败, 失败信息: ${rsp.msg}`);
    } else {
      createMessage.success(`添加机器成功, 机器ID: ${rsp}`);
    }
  }
</script>
